package com.ruoyi.framework.security.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.SignUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    //密钥
    public static final String appSecret = "B092BE52B297DCB08266FD4D71795F80";

    public static final String appkey = "E24F9226C9D71D57F5";

    //开发接口API前缀
    private String pattern = "/api/*";
    private Pattern r = Pattern.compile(pattern);


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        String url = request.getRequestURI();
        log.info("<--- 请求接口:{}", url);
        Matcher m = r.matcher(url);
        if (m.find()){
           // this.checkSignature(request);
        }else{
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }

        }
        chain.doFilter(request, response);
    }


    /**
     * 验证签名
     * @return
     */
    public static boolean checkSignature(HttpServletRequest request) {
        try {
            String headerSignature = request.getHeader(Constants.signature);
            String headerAppkey = request.getHeader(Constants.appkey);
            String headerTimestamp = request.getHeader(Constants.timestamp);
            String headerNoncestr = request.getHeader(Constants.noncestr);
            if (!appkey.equals(headerAppkey)){
                throw new BaseException("appkey错误");
            }

            //因为需要排序，直接使用TreeMap
            Map<String, Object> parms = new TreeMap<>();
            parms.put(Constants.appkey, headerAppkey);
            parms.put(Constants.timestamp, headerTimestamp);
            parms.put(Constants.noncestr, headerNoncestr);

            String str = SignUtil.createLinkString(parms);
            log.info("排序后的值：{}",str);
            str= str+"&appSecret=" + appSecret;
            log.info("加密钥后的排序：{}",str);
            String s = Md5Utils.hash(str).toUpperCase();
            log.info("加密后的签名：{}",s);
            //签名比对
            if (s.equals(headerSignature)) {
                return true;
            }
            return false;
        } catch (Exception e) {
            throw new BaseException("签名失败");
        }
    }
}
